import React, { useState, useEffect, useContext } from 'react'
import styles from './index.less'
import leadScanImg from '@/assets/img/leadToScan.png'
import MyContent from '@/store/my-context'
import { getNowTimeMs } from '@/interfaces/functions'
import LoadingPage from '@/components/loadingPage'
import { getLoginQrKey, getQrImg, getQrState, getAccount } from '@/api'
import IconFont from '@/components/iconfont'
let a: NodeJS.Timeout | null = null
const LoginPage: React.FC = () => {
    const [qrKey, setQrKey] = useState<string | null>(null)
    const [qrImg, setQrImg] = useState<string | null>(null)
    // let qrState:number = 1
    const [qrState, setQrState] = useState<any>(null)
    const [isQrDisable, setIsQrDisable] = useState<boolean>(false)
    const [isNeedLead, setIsNeedLead] = useState<boolean>(true)
    const { state, dispatch } = useContext(MyContent)
    const [isLoading, setIsLoading] = useState<boolean>(true)
    const pollingQrKey = (tQrKey: string | null, ms: number) => {
        if (tQrKey && qrKey === tQrKey) {
            //记录调用时的key，若是跟当前key不同
            //则不轮询状态，防止多次刷新导致多次调用
            a = setTimeout(() => {
                getQrState({
                    key: tQrKey,
                    time: getNowTimeMs()
                }).then((result) => {
                    if (result?.code) {
                        // console.log(result)
                        setQrState(result)
                        if (result.code === 800) {
                            clearPoll()
                            setIsQrDisable(true)
                        } else if (result.code === 803) {
                            clearPoll()
                            getAccount().then(res => {
                                console.log(res)
                                if (res?.account?.id) {
                                    dispatch({
                                        type: 'SET_USERDATA',
                                        value: { userData: { uid: res.account.id } }
                                    })
                                }
                            }, err => console.log(err))
                        } else if (result.code === 801) {
                            clearPoll()
                            return pollingQrKey(tQrKey, 3000)
                        } else if (result.code === 802) {
                            clearPoll()
                            return pollingQrKey(tQrKey, 1000)
                        }
                    } else {
                        setQrState(null)
                        console.log('获取二维码状态失败')
                    }
                }, err => console.log(err))
            }, ms)
        }
    }
    //组件销毁时，结束轮询
    useEffect(() => {
        return clearPoll
    }, [])
    const clearPoll = () => {
        if (a) {
            clearTimeout(a)
            a = null
        }
    }
    useEffect(() => {
        if (!qrState && !state.userData?.uid) {
            clearPoll()
            getLoginQrKey({
                time: getNowTimeMs()
            }).then((result: any) => {
                if (result?.data?.unikey?.length > 0) {
                    setQrKey(result.data.unikey)
                } else {
                    console.log('二维码key获取失败')
                }
            }, err => console.log(err))
        }
        // console.log(qrState)
        // console.log(state.userData?.uid)
    }, [qrState?.code])
    useEffect(() => {
        clearPoll()
        if (qrKey) {
            getQrImg({
                key: qrKey,
                qrimg: true,
                time: getNowTimeMs()
            }).then((result: any) => {
                if (result?.data?.qrimg?.length > 0) {
                    setQrImg(result?.data?.qrimg)
                    setIsQrDisable(false)
                    pollingQrKey(qrKey, 3000)
                } else {
                    console.log('二维码图片获取失败')
                }
            }, err => console.log(err))
        }
    }, [qrKey])
    return (
        <div
            className={styles['thispage']}
        >
            <div
                className={styles['icon-guanbi']}
            >
                <IconFont type={'iconX'} />
            </div>
            <span
                style={{
                    margin: '20% 0 10% 0',
                    display: 'block',
                    fontSize: '20px',
                    textAlign: 'center'
                }}>
                扫码登录
            </span>
            <div
                className={styles['qr-page']}>
                <LoadingPage 
                isLoading={isLoading}
                style={{height:'100%'}} />
                <div
                    className={styles['lead-scan']}
                >
                    <img
                        src={leadScanImg}
                        style={{
                            width: '130px',
                            height: '240px',
                            marginLeft: '50px'
                        }} />
                </div>
                <div
                    className={styles['qrimg']}
                >
                    <img
                        src={qrImg || undefined}
                        className={styles['img']}
                        onLoad={(event: any) => {
                            event.stopPropagation()
                            setIsLoading(false)
                            event = null
                        }}
                    />
                    <div
                        style={{
                            width: '100%',
                            fontSize: '12px',
                            textAlign: 'center',
                            height: '60px',
                            backgroundColor: '#fff'

                        }}>
                        使用
                        <a
                            onClick={(event: any) => {
                                event.stopPropagation()
                                window.open('https://music.163.com/#/download')
                                event = null
                            }}>
                            网易云音乐APP
                        </a>
                        扫码登录
                    </div>
                    {
                        isQrDisable
                        && <div
                            className={styles['img']}
                            style={{
                                position: 'absolute',
                                top: 0,
                                backgroundColor: 'rgba(50,50,50,0.6)',
                                textAlign: 'center'
                            }}>
                            <span
                                style={{
                                    fontSize: '14px',
                                    marginTop: '30%',
                                    display: 'block',
                                    color: '#fff'
                                }}
                            >
                                二维码已失效
                        </span>
                            <a
                                style={{
                                    display: 'inline-block',
                                    marginTop: '5%',
                                    color: '#fff',
                                    backgroundColor: 'rgb(12,115,194)',
                                    borderRadius: '6px',
                                    padding: '5px 25px',
                                    fontSize: '12px'
                                }}
                                onClick={() => {
                                    setQrState(null)
                                }}
                            >
                                点击刷新
                            </a>
                        </div>
                    }
                </div>
            </div>
            <div 
            style={{
                textAlign:'center',
                fontSize:'12px',
                marginTop:'20px'
            }}>
            <a
            style={{
                color:'rgb(51,51,51)'
            }}>
                选择其他登录模式
                <IconFont type={'iconjiantou'}/>
            </a>
            </div>
        </div>
    )
}
export default LoginPage